import React, { forwardRef, useState } from 'react'
import { Form, Select, Input } from 'antd'
import PropTypes from 'prop-types'
import AutoNameInput from './AutoNameInput'
import { checkIdCard } from '@js/identityTest'
import { CaseContext } from '../../../context'
const { Item } = Form
const { Option } = Select
const { TextArea } = Input
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 }
}

// 改变主体
function changeSubject (o, formRef, companyLicenseTypes, licenseTypeList, setModelType) {
  const c = formRef.current
  let licenseType = c.getFieldValue('license_type')
  if (['企业', '非企业组织'].indexOf(o.value) !== -1) {
    licenseType = companyLicenseTypes.indexOf(licenseType) === -1 ? companyLicenseTypes[0] : licenseType
  } else {
    licenseType = licenseTypeList.indexOf(licenseType) === -1 ? licenseTypeList[0] : licenseType
  }
  setModelType(o.value)
  c.setFieldsValue({
    subject_type: o.value,
    subject_type_tag: o.title,
    license_type: licenseType
  })
}

// 验证身份证
function validateLicense (formRef, isPre, rule, value) {
  const type = formRef.current.getFieldValue(['license_type'])
  if (type === '身份证' && value && value.length && !isPre) {
    const e = checkIdCard.test(value)
    if (e) {
      return Promise.reject(new Error(e))
    }
  }
  return Promise.resolve()
}

// 根据主体类型渲染特定字段
function NameInputByType (formRef, isPre, type, companyLicenseTypes, licenseTypeList) {
  let name = '公司名称'
  let legal = '法定代表人'
  let licenseTypes = companyLicenseTypes
  if (type === '自然人') {
    name = '姓名'
    licenseTypes = licenseTypeList
  } else if (type === '非企业组织') {
    name = '组织名称'
    legal = '负责人'
  }
  return (
    <>
      <Item label={name} name='name' rules={[{ required: true, message: `${name}不能为空` }]}>
        <AutoNameInput name={name} formRef={formRef} type={type} />
      </Item>
      <Item label='证件类型' name='license_type'>
        <Select
          placeholder='请选择证件类型' onChange={e => {
            formRef.current.setFieldsValue({ license_type: e })
            formRef.current.validateFields([['license']])
          }}
        >
          {licenseTypes.map((li, i) => (
            <Option value={li} key={li}>{li}</Option>
          ))}
        </Select>
      </Item>
      <Item label='证件号码' name='license' rules={[{ validator: (...args) => validateLicense(formRef, isPre, ...args) }, { required: !isPre, message: '请输入证件号码' }]}>
        <Input placeholder='请输入证件号码' />
      </Item>
      {['企业', '非企业组织'].indexOf(type) !== -1 ? (
        <Item label={legal} name='legal'>
          <Input placeholder={`请输入${legal}`} />
        </Item>
      ) : null}
    </>
  )
}

function Main ({ initialValues, dictionaries, onFinish }, ref) {
  const typeList = dictionaries['主体类型'] || []
  // const finacialCompanyTypes = dictionaries['金融业企业类型'] || []
  const areaList = (dictionaries['所在地'] || []).map(li => li.title)
  const licenseTypeList = (dictionaries['自然人证件类型'] || []).map(li => li.title)
  const companyLicenseTypes = (dictionaries['企业证件类型'] || []).map(li => li.title)
  const [modelType, setModelType] = useState(initialValues.subject_type)
  return (
    <CaseContext.Consumer>
      {({ isPre }) => (
        <Form ref={ref} {...layout} initialValues={initialValues} onFinish={d => onFinish(d)}>
          <Item name='id' noStyle><span /></Item>
          <Item name='subject_type' noStyle><span /></Item>
          <Item label='当事人主体' name='subject_type_tag' rules={[{ required: true }]}>
            <Select placeholder='请选择当事人主体' onChange={v => changeSubject(typeList[v], ref, companyLicenseTypes, licenseTypeList, setModelType)}>
              {typeList.map((li, i) => (
                <Option value={i} key={li.title}>{li.title}</Option>
              ))}
            </Select>
          </Item>
          {NameInputByType(ref, isPre, modelType, companyLicenseTypes, licenseTypeList)}
          <Item label='住所' name='address' rules={[{ required: false, message: '住所不能为空' }]}>
            <TextArea placeholder='请输入住所' style={{ resize: 'none' }} />
          </Item>
          <Item label='当事人所在地' name='area' rules={[{ required: true, message: '当事人所在地不能为空' }]}>
            <Select placeholder='请选择当事人所在地'>
              {areaList.map((li, i) => (
                <Option value={li} key={li}>{li}</Option>
              ))}
            </Select>
          </Item>
          {/* {modelType === '企业' ? (
            <Item label='金融业企业类型' name='finacial_company_type'>
              <Select style={{ width: '100%' }} placeholder='请选择案件涉外类型' allowClear>
                {finacialCompanyTypes.map(li => (
                  <Option key={li.title} value={li.value}>{li.title}</Option>
                ))}
              </Select>
            </Item>
          ) : null} */}
          <Item label='手机号码' name='mobile' rules={[{ pattern: /^1\d{10}$/, message: '手机号码格式不正确' }]}>
            <Input placeholder='请输入手机号码' maxLength={11} />
          </Item>
          <Item label='邮箱' name='email' rules={[{ type: 'email', message: '邮箱格式不正确' }]}>
            <Input placeholder='请输入邮箱' />
          </Item>
          <Item label='其他联系方式' name='tel'>
            <Input placeholder='请输入其他联系方式' />
          </Item>
        </Form>
      )}
    </CaseContext.Consumer>
  )
}

const RefMain = forwardRef(Main)

RefMain.propTypes = {
  initialValues: PropTypes.object,
  dictionaries: PropTypes.object,
  onFinish: PropTypes.func
}

RefMain.defaultProps = {
  initialValues: {},
  dictionaries: {},
  onFinish: () => {}
}

export default RefMain
